package com.zufangbao.earth.web.controller.system;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.utils.StringUtils;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.demo2do.core.web.resolver.Page;
import com.demo2do.core.web.resolver.Secure;
import com.zufangbao.earth.entity.security.Principal;
import com.zufangbao.earth.entity.security.PrincipalSpec;
import com.zufangbao.earth.service.PrincipalService;
import com.zufangbao.earth.util.Md5Util;
import com.zufangbao.sun.entity.company.Company;
import com.zufangbao.sun.entity.company.corp.App;
import com.zufangbao.sun.service.AppService;
import com.zufangbao.sun.service.CompanyService;

@Controller
@MenuSetting("menu-system")
public class PrincipalController {
	@Autowired
	private PrincipalService principalService;
	@Autowired
	private CompanyService companyService;
	@Autowired
	private AppService appService;
	@MenuSetting("submenu-update-password")
	@RequestMapping("/post-update-password")
	public ModelAndView postToUpdatePasswordPage(@Secure Principal principal) {
		ModelAndView result = new ModelAndView("principal/principal-update-password");
		return result;
	}
	
	@RequestMapping(value="/update-password",method=RequestMethod.POST)
	public @ResponseBody String updatePassword(@Secure Principal principal,String oldPassword,String newPassword) {
		return this.principalService.updatePassword(principal,oldPassword,newPassword);
	}
	
	@MenuSetting("submenu-authority-control")
	@RequestMapping(value="/authority-control")
	public ModelAndView userAuthorityControlPage(@Secure Principal principal) {
		List<App> appList = this.appService.loadAll(App.class);
		ModelAndView authorityControlPage = new ModelAndView("principal/principal-authority-control"); 
		authorityControlPage.addObject("appList", appList);
		authorityControlPage.addObject("userRoles", PrincipalSpec.values());
		return authorityControlPage;
	}
	
	@RequestMapping(value="/user-Authority-set",method=RequestMethod.POST)
	public @ResponseBody String userAuthorityControlSet(@Secure Principal principal,
							@RequestParam(value="app",required=false) String app,
							@RequestParam(value="role_name",required=true) String role_name) {
		if(!principal.isSuperRole()){
			return "没有权限的操作";
		}
		App operation_app = this.appService.getAppById(app);
		List<Principal> operationPrincipals = this.principalService.getRoleListByApp(operation_app);
		for(Principal Principal :operationPrincipals){
			Principal.setAuthority(role_name);
			try {
				this.principalService.save(Principal);
			} catch (Exception e) {
				e.printStackTrace();
				return "创建权限操作失败";
			}
		}
		return "创建权限操作成功"; 
	}
	
	@MenuSetting("submenu-role-principal")
	@RequestMapping(value="create-user-role",method=RequestMethod.GET)
	public ModelAndView postToCreateUserRole(){
		ModelAndView result = new ModelAndView("principal/create-principal-role");
		result.addObject("appList",this.appService.loadAll(App.class));
		result.addObject("userRoles",PrincipalSpec.values());
		return result;
	}
	
	@RequestMapping(value="create-principal-user-role",method=RequestMethod.POST)
	public @ResponseBody String createUserRole(String app,String userName,String role){
		if(StringUtils.isEmpty(role)||StringUtils.isEmpty(userName)||StringUtils.isEmpty(app)){
			return "不完整的信息";
		}
		return getCreateUserRoleMessage(app, userName, role);
	}
	
	@RequestMapping(value="create-internal-user-role",method=RequestMethod.POST)
	public @ResponseBody String createInternalUserRole(@Secure Principal principal,
			@RequestParam(value="userName",required=true) String userName){
		if(!principal.isSuperRole()){
			return "无权限的操作";
		}
		return getCreateUserRoleMessage(null, userName,Principal.ROLE_SUPER_USER);
	}

	private String getCreateUserRoleMessage(String app, String userName, String role) {
		Principal principal = this.principalService.getPrincipal(userName);
		if(principal != null){
			return "已存在的用户名";
		}
		return generateUserRole(app, userName, role);
	}

	private String generateUserRole(String app, String userName, String role) {
		Principal principal = new Principal();
		principal.setAuthority(role);
		if(!StringUtils.isEmpty(app)){
			principal.setKeyId(Long.valueOf(app));
		}else{
			principal.setKeyId(null);
		}
		principal.setName(userName);
		String default_password = "123456";
		principal.setPassword(Md5Util.encode(default_password));
		try {
			this.principalService.save(principal);
			return "创建成功，初始密码为"+default_password;
		} catch (Exception e) {
			e.printStackTrace();
			return "创建失败，请重新创建";
		}
	}
	
	@MenuSetting("submenu-internal-role")
	@RequestMapping(value="internal-user-role",method=RequestMethod.GET)
	public ModelAndView internalUserRolePage(){
		ModelAndView result = new ModelAndView("principal/internal-user-role");
		return result;
	}
	
	
	@MenuSetting("submenu-role-list")
	@RequestMapping(value="show-user-list",method=RequestMethod.GET)
	public ModelAndView userList(Page page){
		ModelAndView result = new ModelAndView("principal/user-role-list");
		List<Principal> roleList = getRoleList(page);
		result.addObject("roleList",roleList);
		return result;
	}

	public List<Principal> getRoleList(Page page) {
		com.demo2do.core.persistence.support.Order order = new com.demo2do.core.persistence.support.Order();
		order.add("id", "DESC");
		List<Principal> roleList = this.principalService.list(Principal.class, order,page);
		for(Principal principal : roleList){
			if(principal.isSuperRole()){
				principal.setCompanyName("租房宝");
				continue;
			}
			if(principal.isFinanceRole()){
				Company company = this.companyService.load(Company.class, principal.getKeyId());
				principal.setCompanyName(company.getFullName());
				continue;
			}
			
			App app = this.appService.load(App.class, principal.getKeyId());
			principal.setCompanyName(app.getCompany().getFullName());
			
		}
		return roleList;
	}
}
